/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 * @author gauconpuka
 */
public class ShareResource_TuanDQ {


    // insert Picture
    // -- successful
    public boolean insertPicture() {
        // Instead Input Stream
        FileInputStream fin = null;
        try {
            // Connect Database
            ConnectDatabase myConn = new ConnectDatabase();
            Connection connect = myConn.getConnection();
            // set File need to input to SQL
            File imgfile = new File("E:/Sunset.jpg");
            // set InputStream is this File
            fin = new FileInputStream(imgfile);
            // Execute command to insert image into SQL
            PreparedStatement pre = connect.prepareStatement("insert into ResourceTypeTable(ResourceExtender,ResourceIcon) values(?,?)");
            // Add parameter
            pre.setString(1, "demo");
            pre.setBinaryStream(2, fin, (int) imgfile.length());
            pre.executeUpdate();

            System.out.println("Inserting Successfully!");
            pre.close();

            return true;
        // End to Input
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        finally {
            try {
                fin.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return false;
    }


    // View Image of Icon
    public byte[] viewPicture(String extender) {
        byte[] barray= null;
        try {
            // Connnect Database
            ConnectDatabase myConn = new ConnectDatabase();
            Connection connect = myConn.getConnection();
            // set SQL command
            String sql = "select ResourceIcon from ResourceTypeTable where ResourceExtender="+extender;
            // execute Command
            Statement st = connect.createStatement();
            // Return Result
            ResultSet rs=st.executeQuery(sql);
            // Check more than one result
            while (rs.next()) {
                // get all byte in Field ResourceIcon
               barray = rs.getBytes("ResourceIcon");
            }
            return barray;
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        return barray;
    }
}
